const {secret} = require('./token.js')
const jsonwebtoken = require('jsonwebtoken')
const whiteList = ['/admin/register','/admin/login','/admin/refreshToken','/zzq/login', '/zzq/refresh', '/zzq/login', '/zzq/regCode', '/zzq/emailCode','/zzq/email','/zzq/setpass','/zzq/Account','/zzq/Accountpass','/zzq/upload']

const isWhiteList=(url,whiteList)=>{
    return whiteList.find(item => item === url) ? true : false
}

const auth = async (ctx,next)=>{
    let url = ctx.path
    // 如果在白明单里
    if(isWhiteList(url,whiteList)){
        return await next()
    }else{
        // 如果不在 获取短token
        let refreshToken = ctx.request.headers['authorization']
        if(!refreshToken){
            ctx.body = {
                code:401,
                msg:"没token 请先登录获取token"
            }
        }else{
            // 没有权限拦住
           await jsonwebtoken.verify(refreshToken,secret,async (error)=>{
                if(error){
                    console.log(error)
                    ctx.body = {
                        code:409,
                        msg:"短token过期了 正在判断长token有无过期"
                    }
                }else{
                    return await next()
                }
            })
        }
    }
}
module.exports = auth